import KoaRouter from '@koa/router';

import generateRouter from '@/tools/generateRouter';

import type {
  KoaRoutes,
} from '@/types/koa';

import {
  checkEmailFormat,
  validationUserIsExist,
  validationVerifyCodeIsValidity,

  validateStateIntercept,
} from '@/middleware/validation.middleware';

import {
  emailRegisterVerifyCode,
  graphicsVerifyCode,
} from '@/controller/verify_code.controller';

import {
  findUser,
} from '@/service/user.service';
import {
  RedisDB,
} from '@/db/redis.db';

import {
  VERIFY_CODE_VALIDITY_ERROR,
  EMAIL_EXISTING_ERROR,
} from '@/constant/error/validator.error';

const router = new KoaRouter();

const routes: KoaRoutes[] = [
  {
    method: 'get',
    path: '/email/register/verify_code',
    middleware: [
      checkEmailFormat,

      validationVerifyCodeIsValidity({ redisDB: RedisDB, prefix: 'EMAIL_REGISTER_VERIFY_CODE_', key: 'email' }),
      validateStateIntercept({ state: true, validateKey: 'verifyCodeIsValidity', message: VERIFY_CODE_VALIDITY_ERROR }),

      validationUserIsExist({ service: findUser, key: 'email' }),
      validateStateIntercept({ state: true, validateKey: 'userIsExist', message: EMAIL_EXISTING_ERROR }),
    ],
    controller: emailRegisterVerifyCode,
  },
  {
    method: 'get',
    path: '/graphics/verify_code',
    middleware: [],
    controller: graphicsVerifyCode,
  },
];

generateRouter(router, routes);

export default router;
